
pub struct BytecodeReader<'a> {
    code: &'a [u8],
    pc: usize
}

impl<'a> BytecodeReader<'a> {
    pub fn new() -> BytecodeReader<'a> {
        BytecodeReader { code: &[], pc: 0 }
    }

    pub fn get_pc(&self) -> usize {
        self.pc
    }
 
    pub fn reset(&mut self, code: &'a [u8], pc: usize) {
        self.code = code;
        self.pc = pc;
    }

    pub fn read_u8(&mut self) -> u8 {
        let i = self.code[self.pc];
        self.pc += 1;
        i
    }

    pub fn read_i8(&mut self) -> i8 {
        self.read_u8() as i8
    }


    pub fn read_u16(&mut self) -> u16 {
        let byte1 = self.read_u8() as u16;
        let byte2 = self.read_u8() as u16;
        (byte1 << 8) | byte2
    }

    pub fn read_i16(&mut self) -> i16 {
        self.read_u16() as i16
    }

    pub fn read_i32(&mut self) -> i32 {
        let byte1 = self.read_u8() as i32;
        let byte2 = self.read_u8() as i32;
        let byte3 = self.read_u8() as i32;
        let byte4 = self.read_u8() as i32;
        (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4
    }

    pub fn read_i32s(&mut self, n: usize) -> Vec<i32> {
        (0..n).map(|_| self.read_i32()).collect()
    }

    // 跳过填充，保证为4的倍数
    pub fn skip_padding(&mut self) {
        while self.pc % 4 != 0 {
           let _ = self.read_u8(); 
        }
    }
}